

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="一又四分之一">
  <meta name="keywords" content="">
  
    <meta name="description" content="PHP操作1. mysqli_connect() 连接数据库2. mysqli_close() 关闭数据库12345678910111213141516171819202122&lt;?php$servername &#x3D; &quot;localhost&quot;;  &#x2F;&#x2F; MySQL 服务器地址$username &#x3D; &quot;root&quot;;         &#x2F;&#x2F; 数据库用户名$pass">
<meta property="og:type" content="article">
<meta property="og:title" content="php常用数据库操作">
<meta property="og:url" content="https://one-and-one-fourth.gitee.io/2024/02/03/PHP%E6%93%8D%E4%BD%9C/index.html">
<meta property="og:site_name" content="one-and-one-fourth">
<meta property="og:description" content="PHP操作1. mysqli_connect() 连接数据库2. mysqli_close() 关闭数据库12345678910111213141516171819202122&lt;?php$servername &#x3D; &quot;localhost&quot;;  &#x2F;&#x2F; MySQL 服务器地址$username &#x3D; &quot;root&quot;;         &#x2F;&#x2F; 数据库用户名$pass">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-02-03T13:02:06.000Z">
<meta property="article:modified_time" content="2024-02-15T02:24:32.069Z">
<meta property="article:author" content="一又四分之一">
<meta property="article:tag" content="php">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>php常用数据库操作 - one-and-one-fourth</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"one-and-one-fourth.gitee.io","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  



  
<meta name="generator" content="Hexo 7.1.1"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>one-and-one-fourth</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="php常用数据库操作"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-02-03 21:02" pubdate>
          2024年2月3日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          1.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          13 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">php常用数据库操作</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="PHP操作"><a href="#PHP操作" class="headerlink" title="PHP操作"></a>PHP操作</h1><h2 id="1-mysqli-connect-连接数据库"><a href="#1-mysqli-connect-连接数据库" class="headerlink" title="1. mysqli_connect() 连接数据库"></a>1. <code>mysqli_connect()</code> 连接数据库</h2><h2 id="2-mysqli-close-关闭数据库"><a href="#2-mysqli-close-关闭数据库" class="headerlink" title="2. mysqli_close() 关闭数据库"></a>2. <code>mysqli_close()</code> 关闭数据库</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-variable">$servername</span> = <span class="hljs-string">&quot;localhost&quot;</span>;  <span class="hljs-comment">// MySQL 服务器地址</span><br><span class="hljs-variable">$username</span> = <span class="hljs-string">&quot;root&quot;</span>;         <span class="hljs-comment">// 数据库用户名</span><br><span class="hljs-variable">$password</span> = <span class="hljs-string">&quot;password&quot;</span>;     <span class="hljs-comment">// 数据库密码</span><br><span class="hljs-variable">$dbname</span> = <span class="hljs-string">&quot;mydatabase&quot;</span>;     <span class="hljs-comment">// 数据库名</span><br><br><span class="hljs-comment">// 建立与 MySQL 数据库服务器的连接</span><br><span class="hljs-variable">$conn</span> = <span class="hljs-title function_ invoke__">mysqli_connect</span>(<span class="hljs-variable">$servername</span>, <span class="hljs-variable">$username</span>, <span class="hljs-variable">$password</span>, <span class="hljs-variable">$dbname</span>);<br><br><span class="hljs-comment">// 检查连接是否成功</span><br><span class="hljs-keyword">if</span> (!<span class="hljs-variable">$conn</span>) &#123;<br>    <span class="hljs-keyword">die</span>(<span class="hljs-string">&quot;连接失败: &quot;</span> . <span class="hljs-title function_ invoke__">mysqli_connect_error</span>());<br>&#125;<br><br><span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;连接成功！&quot;</span>;<br><br><span class="hljs-comment">// 在这里可以执行数据库操作</span><br><br><span class="hljs-comment">// 关闭与 MySQL 数据库服务器的连接</span><br><span class="hljs-title function_ invoke__">mysqli_close</span>(<span class="hljs-variable">$conn</span>);<br><span class="hljs-meta">?&gt;</span><br><br></code></pre></td></tr></table></figure>



<p><code>mysqli_num_rows()</code> 是 PHP 中用于获取查询结果中行数的函数，它是 MySQLi（MySQL Improved Extension）扩展库的一部分。MySQLi 是 PHP 提供的一个强大且面向对象的扩展，用于与 MySQL 数据库进行交互。</p>
<p><code>mysqli_num_rows</code> 函数的语法如下：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-title function_ invoke__">mysqli_num_rows</span>(<span class="hljs-variable">$result</span>);<br></code></pre></td></tr></table></figure>

<p>其中：</p>
<ul>
<li><code>$result</code> 是一个结果对象，它表示从数据库中返回的查询结果集。</li>
</ul>
<h2 id="3-mysqli-num-rows-查询结果集中的行数"><a href="#3-mysqli-num-rows-查询结果集中的行数" class="headerlink" title="3. mysqli_num_rows 查询结果集中的行数"></a>3. <code>mysqli_num_rows</code> 查询结果集中的行数</h2><p>函数返回查询结果集中的行数，即结果集中包含多少条记录。如果查询失败或返回的结果集为空，则该函数返回 0。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-comment">// 创建数据库连接</span><br><span class="hljs-variable">$connection</span> = <span class="hljs-title function_ invoke__">mysqli_connect</span>(<span class="hljs-string">&#x27;localhost&#x27;</span>, <span class="hljs-string">&#x27;username&#x27;</span>, <span class="hljs-string">&#x27;password&#x27;</span>, <span class="hljs-string">&#x27;database&#x27;</span>);<br><br><span class="hljs-comment">// 检查连接是否成功</span><br><span class="hljs-keyword">if</span> (<span class="hljs-title function_ invoke__">mysqli_connect_errno</span>()) &#123;<br>    <span class="hljs-keyword">die</span>(<span class="hljs-string">&#x27;连接数据库失败: &#x27;</span> . <span class="hljs-title function_ invoke__">mysqli_connect_error</span>());<br>&#125;<br><br><span class="hljs-comment">// 执行查询</span><br><span class="hljs-variable">$query</span> = <span class="hljs-string">&quot;SELECT * FROM users&quot;</span>;<br><span class="hljs-variable">$result</span> = <span class="hljs-title function_ invoke__">mysqli_query</span>(<span class="hljs-variable">$connection</span>, <span class="hljs-variable">$query</span>);<br><br><span class="hljs-comment">// 获取查询结果中的行数</span><br><span class="hljs-variable">$num_rows</span> = <span class="hljs-title function_ invoke__">mysqli_num_rows</span>(<span class="hljs-variable">$result</span>);<br><br><span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;查询结果中共有 <span class="hljs-subst">&#123;$num_rows&#125;</span> 条记录\n&quot;</span>;<br><br><span class="hljs-comment">// 关闭数据库连接</span><br><span class="hljs-title function_ invoke__">mysqli_close</span>(<span class="hljs-variable">$connection</span>);<br><br></code></pre></td></tr></table></figure>

<h2 id="4-mysqli-select-db-选择数据库的函数"><a href="#4-mysqli-select-db-选择数据库的函数" class="headerlink" title="4. mysqli_select_db 选择数据库的函数"></a>4. <code>mysqli_select_db</code> 选择数据库的函数</h2><p>是 PHP 中用于选择数据库的函数。它用于在连接到 MySQL 数据库后，选择要操作的特定数据库。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-keyword">bool</span> <span class="hljs-title function_ invoke__">mysqli_select_db</span> ( mysqli <span class="hljs-variable">$link</span> , <span class="hljs-keyword">string</span> <span class="hljs-variable">$dbname</span> )<br></code></pre></td></tr></table></figure>

<p>参数说明：</p>
<ul>
<li><code>$link</code>：必需，一个有效的 MySQL 连接对象。</li>
<li><code>$dbname</code>：必需，要选择的数据库名称。</li>
</ul>
<p>返回值：</p>
<ul>
<li>如果选择数据库成功，则返回 true。</li>
<li>如果选择数据库失败，则返回 false。</li>
</ul>
<hr>
<h2 id="5-mysqli-query-常规的插入查找等"><a href="#5-mysqli-query-常规的插入查找等" class="headerlink" title="5. mysqli_query  常规的插入查找等"></a>5. mysqli_query  常规的插入查找等</h2><p> 是 PHP 中用于执行 SQL 查询的函数，它是 MySQLi（MySQL Improved Extension）扩展库的一部分。MySQLi 是 PHP 提供的一个强大且面向对象的扩展，用于与 MySQL 数据库进行交互。</p>
<p><code>mysqli_query</code> 函数的语法如下：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-title function_ invoke__">mysqli_query</span>(<span class="hljs-variable">$connection</span>, <span class="hljs-variable">$query</span>);<br></code></pre></td></tr></table></figure>

<p>其中：</p>
<ul>
<li><code>$connection</code> 是一个数据库连接对象，它表示与 MySQL 数据库建立的连接。通常通过 <code>mysqli_connect</code> 或 <code>mysqli_init</code> 函数创建连接对象。</li>
<li><code>$query</code> 是要执行的 SQL 查询语句。</li>
</ul>
<p><code>mysqli_query</code> 函数执行指定的 SQL 查询，并返回一个结果对象或布尔值，具体取决于查询的类型和执行结果。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-comment">// 创建数据库连接</span><br><span class="hljs-variable">$connection</span> = <span class="hljs-title function_ invoke__">mysqli_connect</span>(<span class="hljs-string">&#x27;localhost&#x27;</span>, <span class="hljs-string">&#x27;username&#x27;</span>, <span class="hljs-string">&#x27;password&#x27;</span>, <span class="hljs-string">&#x27;database&#x27;</span>);<br><br><span class="hljs-comment">// 检查连接是否成功</span><br><span class="hljs-keyword">if</span> (<span class="hljs-title function_ invoke__">mysqli_connect_errno</span>()) &#123;<br>    <span class="hljs-keyword">die</span>(<span class="hljs-string">&#x27;连接数据库失败: &#x27;</span> . <span class="hljs-title function_ invoke__">mysqli_connect_error</span>());<br>&#125;<br><br><span class="hljs-comment">// 执行查询</span><br><span class="hljs-variable">$query</span> = <span class="hljs-string">&quot;SELECT * FROM users&quot;</span>;<br><span class="hljs-variable">$result</span> = <span class="hljs-title function_ invoke__">mysqli_query</span>(<span class="hljs-variable">$connection</span>, <span class="hljs-variable">$query</span>);<br><br><span class="hljs-comment">// 处理查询结果</span><br><span class="hljs-keyword">if</span> (<span class="hljs-variable">$result</span>) &#123;<br>    <span class="hljs-comment">// 读取结果集中的数据</span><br>    <span class="hljs-keyword">while</span> (<span class="hljs-variable">$row</span> = <span class="hljs-title function_ invoke__">mysqli_fetch_assoc</span>(<span class="hljs-variable">$result</span>)) &#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-variable">$row</span>[<span class="hljs-string">&#x27;username&#x27;</span>] . <span class="hljs-string">&quot;\n&quot;</span>;<br>    &#125;<br>&#125; <span class="hljs-keyword">else</span> &#123;<br>    <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;查询失败: &#x27;</span> . <span class="hljs-title function_ invoke__">mysqli_error</span>(<span class="hljs-variable">$connection</span>);<br>&#125;<br><br><span class="hljs-comment">// 关闭数据库连接</span><br><span class="hljs-title function_ invoke__">mysqli_close</span>(<span class="hljs-variable">$connection</span>);<br><br></code></pre></td></tr></table></figure>



<h2 id="6-header"><a href="#6-header" class="headerlink" title="6. header( )"></a>6. header( )</h2> <figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs php"> <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;&lt;script&gt;window.location.href = &quot;../index.php&quot;;&lt;/script&gt;&#x27;</span>;<br><span class="hljs-comment">// 上面的语句可以替代下面的转向</span><br> <span class="hljs-title function_ invoke__">header</span>(<span class="hljs-string">&#x27;Location:  ../index.php&#x27;</span>);<br></code></pre></td></tr></table></figure>

<p>产生原因：由于想在进行数据库的读写之后，从 <code>php</code> 页面转到前端页面，使用 <code>header()</code> 不会执行他前面的 <code>echo</code> 语句，故此</p>
<h2 id="7-防止-sql-注入"><a href="#7-防止-sql-注入" class="headerlink" title="7.防止 sql 注入"></a>7.防止 sql 注入</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-keyword">include_once</span> <span class="hljs-string">&quot;../variable.php&quot;</span>;<br><br><span class="hljs-variable">$conn</span> = <span class="hljs-title function_ invoke__">mysqli_connect</span>(<span class="hljs-variable">$mysql_hostname</span>, <span class="hljs-variable">$mysql_username</span>, <span class="hljs-variable">$mysql_password</span>, <span class="hljs-variable">$mysql_database</span>);<br><span class="hljs-keyword">if</span>(!<span class="hljs-variable">$conn</span>)&#123;<br>  <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;数据库&quot;</span>.<span class="hljs-variable">$mysql_database</span>.<span class="hljs-string">&quot;连接失败&quot;</span>;<br>  <span class="hljs-keyword">exit</span>();<br>&#125;<br><span class="hljs-keyword">else</span> <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;连接数据库&quot;</span>.<span class="hljs-variable">$mysql_database</span>.<span class="hljs-string">&quot;成功&quot;</span>;<br><br><span class="hljs-keyword">if</span>(<span class="hljs-keyword">isset</span>(<span class="hljs-variable">$_POST</span>[<span class="hljs-string">&#x27;text&#x27;</span>]) &amp;&amp; <span class="hljs-keyword">isset</span>(<span class="hljs-variable">$_POST</span>[<span class="hljs-string">&#x27;input&#x27;</span>]))&#123;<br>  <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;&lt;script&gt;alert(&#x27;提交&#x27;);&lt;/script&gt;&quot;</span>;<br>  <span class="hljs-variable">$cont1</span> = <span class="hljs-title function_ invoke__">mysqli_real_escape_string</span>(<span class="hljs-variable">$conn</span>, <span class="hljs-variable">$_POST</span>[<span class="hljs-string">&#x27;text&#x27;</span>]);<br>  <span class="hljs-variable">$cont2</span> = <span class="hljs-title function_ invoke__">mysqli_real_escape_string</span>(<span class="hljs-variable">$conn</span>, <span class="hljs-variable">$_POST</span>[<span class="hljs-string">&#x27;input&#x27;</span>]);<br>  <br>  <span class="hljs-variable">$sql</span> = <span class="hljs-string">&quot;INSERT INTO essy (column1, column2) VALUES (?, ?)&quot;</span>;<br>  <span class="hljs-variable">$stmt</span> = <span class="hljs-title function_ invoke__">mysqli_prepare</span>(<span class="hljs-variable">$conn</span>, <span class="hljs-variable">$sql</span>);<br>  <span class="hljs-title function_ invoke__">mysqli_stmt_bind_param</span>(<span class="hljs-variable">$stmt</span>, <span class="hljs-string">&quot;ss&quot;</span>, <span class="hljs-variable">$cont1</span>, <span class="hljs-variable">$cont2</span>);<br>  <span class="hljs-variable">$result</span> = <span class="hljs-title function_ invoke__">mysqli_stmt_execute</span>(<span class="hljs-variable">$stmt</span>);<br>  <br>  <span class="hljs-keyword">if</span>(!<span class="hljs-variable">$result</span>)&#123;<br>    <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;插入数据时发生错误：&quot;</span> . <span class="hljs-title function_ invoke__">mysqli_error</span>(<span class="hljs-variable">$conn</span>);<br>  &#125;<br>  <span class="hljs-keyword">else</span>&#123;<br>    <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;插入数据成功&quot;</span>;<br>  &#125;<br>&#125;<br><span class="hljs-keyword">else</span>&#123;<br>  <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;&lt;script&gt;alert(&#x27;提交错误&#x27;);&lt;/script&gt;&quot;</span>;<br>&#125;<br><br><span class="hljs-title function_ invoke__">mysqli_close</span>(<span class="hljs-variable">$conn</span>);<br><span class="hljs-meta">?&gt;</span><br><br></code></pre></td></tr></table></figure>

<hr>
<p><code>mysqli_real_escape_string()</code>: </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs php">函数的作用就是将字符串中的特殊字符进行转义，使其成为合法的 SQL 字符串。转义后的字符串可以安全地插入到 SQL 查询语句中，而不会引发 SQL 注入问题。<br>该函数接受两个参数：第一个是数据库连接对象，第二个是要转义的字符串。函数会返回转义后的字符串。<br></code></pre></td></tr></table></figure>

<hr>
<p><code>mysqli_prepare()</code> :</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs php">该函数用于准备 SQL 查询语句，返回一个 mysqli_stmt 对象。<br>    <span class="hljs-title function_ invoke__">mysqli_prepare</span>() 接受两个参数：<br>       第一个参数是数据库连接对象，<br>       第二个参数是要执行的 SQL 查询语句（参数使用占位符 <span class="hljs-string">&quot;?&quot;</span> 表示）<br></code></pre></td></tr></table></figure>

<p>这种格式可以提高执行查询的效率，并提高应用程序的安全性。</p>
<p>为后面的 <code>mysqli_stmt_bind_param</code>( )  <code>mysqli_stmt_execute()</code> 做准备</p>
<hr>
<p><code>mysqli_stmt_bind_param</code>( ) :</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs php">	用于绑定参数到准备好的查询语句中。<br>    它接受三个参数：<br>        第一个参数是 mysqli_stmt 对象，<br>        第二个参数是参数类型的字符串，<br>        第三个参数是要绑定的参数<br> <br>第二个参数类型：<br>    字符串类型：s<br>    整数类型：i<br>    双精度浮点类型：d<br>    布尔类型：b<br>第二个参数是根据第三个要绑定的来确定的，对应的是相应数据库中的类型，因此易知，第三个三数可以是多个值，即对应表中的不同列<br></code></pre></td></tr></table></figure>

<p>只是绑定，并没有进行插入等操作，绑定之后通过 <code>mysqli_stmt_execute()</code> 来执行 <strong>sql</strong> 语句中的操作</p>
<p>具体根据 <code>mysqli_prepare()</code> 中的 <strong>sql</strong> 进行的</p>
<hr>
<p><code>mysqli_stmt_execute()</code></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs php">用于执行准备好的查询语句。<br>   它接受一个参数，即 mysqli_stmt 对象<br>       <br>   返回布尔值<br></code></pre></td></tr></table></figure>

<hr>
<p>以上四者搭配使用，一定程度上减小了一点点 <strong>sql</strong> 注入</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/php/" class="category-chain-item">php</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/php/" class="print-no-link">#php</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>php常用数据库操作</div>
      <div>https://one-and-one-fourth.gitee.io/2024/02/03/PHP操作/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>一又四分之一</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年2月3日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/02/03/linux%E7%9F%A5%E8%AF%86%E6%B1%87%E6%80%BB/" title="linux知识汇总">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">linux知识汇总</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/02/03/mysql/" title="mysql">
                        <span class="hidden-mobile">mysql</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
